package leetcode;

public class SwapPairs {

    static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode swapPairs(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode res = head.next;
        ListNode preHead = new ListNode(0);
        ListNode mid = head;
        ListNode curr = head.next;
        while (curr != null){
            preHead.next = curr;
            mid.next = curr.next;
            curr.next = mid;
            if(mid.next == null){
                break;
            }else{
                preHead = mid;
                curr = mid.next.next;
                mid = mid.next;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        ListNode node = new ListNode(0);
        ListNode preNode = node;
        for(int i = 0; i < arr.length; i ++){
            node.next = new ListNode(arr[i]);
            node = node.next;
        }
        new SwapPairs().swapPairs(preNode.next);

    }

}
